/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package domain;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ParaSait
 */
public class DirectoryListener_ extends Thread {

    private Client client;
    private boolean run;
    private boolean activated;
    private Path directory;
    private WatchService watcher;
    private WatchKey key;

    public DirectoryListener_(Client client) {
        this.client = client;
        this.directory = null;
        this.watcher = null;
        //this.key = null;
    }

    public void setDirectory(String path) {
        try {
            System.out.println("Setting dir: " + path);
            //directory = Paths.get(client.getRootDirectory());
            directory = Paths.get(path);
            watcher = FileSystems.getDefault().newWatchService();
            key = directory.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        } catch (IOException ex) {
            Logger.getLogger(DirectoryListener.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void run() {
        setRunning(true);

        while (run) {
            System.out.println("Listener activated: " + activated);
            System.out.println("Client synching: " + client.isSynchronizing());
            System.out.println((directory != null) + ", " + (watcher != null));
            if (activated) {
                if (directory != null && watcher != null) {
                    try {
                        //key = watcher.take();
                        key = watcher.poll(1000, TimeUnit.MILLISECONDS);
                        System.out.println("asdf");
                    } catch (InterruptedException x) {
                        x.printStackTrace();
                        setRunning(false);
                    }
                    
                    System.out.println("yarrr");

                    if (!client.isSynchronizing()) {
                        System.out.println("Events:");
                        for (WatchEvent<?> event : key.pollEvents()) {
                            WatchEvent.Kind<?> kind = event.kind();
                            WatchEvent<Path> ev = (WatchEvent<Path>) event;
                            Path filename = ev.context();
                            File file = new File(filename.toUri());
                            
                            System.out.println("- " + ev.context().toString() + " (" + event.kind().toString() + ")" );

                            if (!file.isDirectory()) // voorlopig nog geen subdirectories
                            {
                                //een verandering getName wordt getAbsolutePath
                                if (kind == ENTRY_CREATE) {
                                    client.sendFile(file.getAbsolutePath());
                                } else if (kind == ENTRY_DELETE) {
                                    client.deleteServerFile(file.getAbsolutePath());
                                } else if (kind == ENTRY_MODIFY) {
                                    client.deleteServerFile(file.getAbsolutePath());
                                    client.sendFile(file.getAbsolutePath());
                                }
                            }

                            boolean valid = key.reset();
                            if (!valid) {
                                break;
                            }
                        }
                    }
                    
                    System.out.println("matey");
                }
            }
            
            try {
                System.out.println("hush hush... now you sleep");
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(ServerListener.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        System.out.println("surstromming I stopped");
    }

    public void setRunning(boolean run) {
        System.out.println("SURSTROMMING: " + run);
        this.run = run;
    }

    public void setActivated(boolean activated) {
        System.out.println("SURSTROMMING2: " + run);
        this.activated = activated;
    }
}
